
#include <BFont>
#include <BPainter>
#include <BTextEdit>
#include <BLayout>

#include "OperaStackDialog.h"

OperaStackDialog::OperaStackDialog(BWidget* parent) : BDialog(parent)
{
	this->setTitle("Opera-Stack");

	_listWidget = new BListWidget();
	_listWidget->setPerch(10);

	BLayout* layout = new BLayout(this);
	layout->setWidget(_listWidget);
	_textEdit = 0;

	connect(this, Signal_AssetChanged, &OperaStackDialog::slotAssetChanged);
	connect(_listWidget, Signal_Framed, &OperaStackDialog::slotListWidgetFramed);
}
OperaStackDialog::~OperaStackDialog()
{

}

void OperaStackDialog::freshOperaList()
{
	_listWidget->clearItems();
	bool dark = false;
	BReal time = 0;
	for (int i = 0; i < _textEdit->operaCount(); i++)
	{
		const BOpera* opera = _textEdit->opera(i);
		if (time == 0)
			time = opera->time;
		else if (time != opera->time)
			dark = !dark;
		BString text;
		switch (opera->mode)
		{
		case BOpera::Mode_Input:
			text << "input";
			break;
		case BOpera::Mode_Insert:
			text << "insert";
			break;
		case BOpera::Mode_Remove:
			text << "remove";
			break;
		case BOpera::Mode_Delete:
			text << "delete";
			break;
		default:
			break;
		}
		text << ' ' << opera->line << ':' << opera->index << '(' << opera->text.count() << ')';
		BListItem* item = _listWidget->addItem(text);
		item->setAsset(opera);
		if (dark)
			item->setBackground(200, 210, 220);
	}
}

void OperaStackDialog::slotAssetChanged(BObject* object, const BValue& value)
{
	BTextEdit* textEdit = value;
	if (_textEdit != textEdit)
	{
		if (_textEdit)
		{
			disconnect(_textEdit);
			_listWidget->clearItems();
		}
		_textEdit = textEdit;
		if (_textEdit)
		{
			connect(_textEdit, Signal_Opera, &OperaStackDialog::slotTextEditOpera);
			freshOperaList();
		}
	}
}
void OperaStackDialog::slotTextEditOpera(BTextEdit* textEdit, const BValue& value)
{
	freshOperaList();
}
void OperaStackDialog::slotListWidgetFramed(BObject* object, const BValue& value)
{
	if (_textEdit)
	{
		int operaIndex = _textEdit->operaIndex();
		BPainter painter(_listWidget);
		const BFont* font = painter.realFont();
		BRect leftRect = this->rect(Part_Left);
		if (BListItem* item = _listWidget->item(operaIndex))
		{
			BRect rect = item->rect();
			rect.left() = leftRect.left();
			rect.right() = leftRect.right();
			rect.move(0, -font->size() / 2);
			painter.setColor(200, 0, 0);
			painter.drawGraph(rect, Graph_Arrow_Right_Fill);
		}
		else
		{
			BRect area = _listWidget->area();
			BRect rect(leftRect.right() - font->size(), area.bottom() - font->size() / 2, font->size(), font->size());
			painter.setColor(200, 0, 0);
			painter.drawGraph(rect, Graph_Arrow_Right_Fill);
		}
	}
}
